import React, { FC, useState, ChangeEvent } from 'react'
import { Button, Typography, Space, Input, message } from 'antd'
import { LeftOutlined, EditOutlined, LoadingOutlined } from '@ant-design/icons'
import { useNavigate, useParams } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { useRequest, useKeyPress, useDebounceEffect } from 'ahooks'

import styles from './EditHeader.module.scss'

import { changePageTitle } from '../../../store/pageInfoReducer'

// *自定义Hook
import useGetPageInfo from '../../../hooks/useGetPageInfo'
import useGetComponentsInfo from '../../../hooks/useGetComponentsInfo'

// *service
import { updateQuestionListService } from '../../../services/question'

// *工具栏
import EditToolbar from './EditToolbar'

const { Title } = Typography

//* 显示和修改标题
const TitleElem: FC = () => {
  const { title } = useGetPageInfo()
  const dispatch = useDispatch()

  // 修改标题
  const [editState, setEditState] = useState(false)

  // *Input标题修改事件
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    const newTitle = event.target.value.trim()
    if (!newTitle) return
    dispatch(changePageTitle(newTitle))
  }

  // *editState 的值为true 显示input输入框,false 显示标题
  if (editState) {
    return (
      <Input
        value={title}
        onChange={handleChange}
        onPressEnter={() => setEditState(false)}
        onBlur={() => setEditState(false)}
      />
    )
  }

  return (
    <Space>
      <Title>{title}</Title>
      <Button
        icon={<EditOutlined />}
        size="small"
        type="text"
        onClick={() => setEditState(true)}
      ></Button>
    </Space>
  )
}

// *保存按钮
const SaveButton: FC = () => {
  // ? 保存什么信息--pageInfo &&  componentList[]
  // ? 通过什么保存信息--问卷的唯一标识 id,id存在于导航地址
  const { componentList = [] } = useGetComponentsInfo()
  const pageInfo = useGetPageInfo()
  const { id } = useParams()

  // *保存
  const { loading, run: save } = useRequest(
    async () => {
      // *执行保存
      if (!id) return
      await updateQuestionListService(id, {
        ...pageInfo,
        componentList,
      })
    },
    { manual: true }
  )

  // *快捷键
  useKeyPress(['ctrl.s', 'meta.s'], (event: KeyboardEvent) => {
    event.preventDefault() //阻止默认事件
    if (!loading) save() //防止连续触发
  })

  //* 自定保存
  //useDebounceEffect既然有useEffect的功能也有防抖的功能,第三个参数为wait等待时间
  useDebounceEffect(
    () => {
      save()
    },
    [componentList, pageInfo],
    { wait: 1000 }
  )

  return (
    <Button onClick={save} disabled={loading} icon={loading ? <LoadingOutlined /> : null}>
      保存
    </Button>
  )
}

// *发布按钮
const PublishButton: FC = () => {
  const nav = useNavigate()
  // 删除---假删除 isDeleted = true(更新)
  // 发布---isPublish = true(更新)
  const { componentList = [] } = useGetComponentsInfo()
  const pageInfo = useGetPageInfo()
  const { id } = useParams()

  // *保存
  const { loading, run: pub } = useRequest(
    async () => {
      // *执行保存
      if (!id) return
      await updateQuestionListService(id, {
        ...pageInfo,
        componentList,
        isPublished: true, //标志着问卷已经被发布
      })
    },
    {
      manual: true,
      onSuccess() {
        message.success('发布成功')
        // 发布成功==>跳转统计stat页面
        nav('/question/stat/' + id)
      },
    }
  )

  return (
    <Button type="primary" onClick={pub} disabled={loading}>
      发布
    </Button>
  )
}

// * 编辑器头部
const EditHeader: FC = () => {
  const nav = useNavigate()
  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  )
}

export default EditHeader
